package com.store.webstore.controller;

import com.store.webstore.entity.MessageResult;
import com.store.webstore.entity.User;
import com.store.webstore.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆功能控制层
 */
@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @RequestMapping("/login/view")
    public String skipLogin(){
        return "login";
    }



    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public MessageResult login(User user, HttpServletRequest req, HttpSession session, HttpServletResponse res){
        MessageResult result = new MessageResult();
        try {
            User loginUser = loginService.findUserByUsername(user.getUsername());
            if(loginUser == null){
                result.setErrorMessage("用户名不正确");
                result.setSuccess(false);
                return result;
            }else{
                if (user.getPassword().equals(loginUser.getPassword())){
                    //用户名,密码一致,登陆成功,跳转到首页,用户信息存到session中
                    session.setAttribute("existUser",user);
                    result.setSuccess(true);
                    res.sendRedirect("index");
                    return result;
                }else{
                    //密码不一致
                    result.setErrorMessage("密码错误");
                    result.setSuccess(false);
                    return result;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorMessage("登陆错误");
        }
        return result;
    }



}
